package com.shuai.chatroom.controller;

import com.shuai.chatroom.common.AppConstant;
import com.shuai.chatroom.common.HttpResult;
import com.shuai.chatroom.entity.UserInfo;
import com.shuai.chatroom.exception.ControllerException;
import com.shuai.chatroom.service.SessionsService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/session")
public class SessionController {
    @Resource
    private SessionsService sessionsService;

    @RequestMapping("/list")
    public HttpResult getSessionsList(HttpServletRequest request) throws ControllerException {
        HttpSession session = request.getSession(false);
        UserInfo userInfo;
        if (session == null
                || (userInfo = (UserInfo) session.getAttribute(AppConstant.USER_SESSION_KEY)) == null
                || userInfo.getUId() == null) {
            throw new ControllerException("非法请求！");
        }
        return HttpResult.success(sessionsService.getSessionInfoVOS(userInfo.getUId()));
    }

    @RequestMapping("/add")
    public HttpResult addSession(HttpServletRequest request, Integer toUId) throws ControllerException {
        if (toUId == null) {
            throw new ControllerException("非法参数！");
        }
        HttpSession session = request.getSession(false);
        UserInfo userInfo;
        if (session == null || (userInfo = (UserInfo) session.getAttribute(AppConstant.USER_SESSION_KEY)) == null || userInfo.getUId() == null) {
            throw new ControllerException("非法请求！");
        }
        return HttpResult.success(sessionsService.addSession(userInfo.getUId(), toUId));
    }
}
